//
//  CLBuleToothBraceletNetTool.m
//  toroBracelet
//
//  Created by 丁益 on 16/8/17.
//  Copyright © 2016年 celi. All rights reserved.
//  与蓝牙手环通讯工具类

#import "CLBuleToothBraceletNetTool.h"
#import "CLSeverTool.h"

typedef void (^ErrorBlock)(NSError *);

@interface CLBuleToothBraceletNetTool()<CLBuleToothToolDelegate>

@property (nonatomic ,strong) CLBuleToothTool *buleToothTool;
@property (nonatomic ,copy) scanBuleToothBraceletComplete scanSuccess;
@property (nonatomic ,copy) connectBuleToothSuccess connectSuccess;
@property (nonatomic, copy) ErrorBlock errorBlock;
@end

@implementation CLBuleToothBraceletNetTool

static id _instace = nil;
- (id)init{
    
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        _instace = [super init];
        _buleToothTool = [CLBuleToothTool sharedBuleToothTool];
        _buleToothTool.delegate = self;
    });
    return _instace;
}

+ (id)sharedBuleToothBraceletNetTool{

    return  [[self alloc] init];
}


- (void)scanBuleToothBracelet:(scanBuleToothBraceletComplete)scanSuccess scanFailure:(void (^)(NSError *))scanFailure{
    
    [_buleToothTool StartScanBuleToothDevice];
    self.scanSuccess = scanSuccess;
}

- (void)connectBuleToothBraceletWithperipheral:(CBPeripheral *)peripheral connectSuccess:(connectBuleToothSuccess)connectSuccess connectFailure:(void (^)(NSError *))connectFailure{
    
    //连接蓝牙外设
    [self.buleToothTool connect:peripheral];
    
    self.connectSuccess = connectSuccess;
    self.errorBlock = connectFailure;
    
}

- (void)cancelBuleToothBracelet{

    [self.buleToothTool cancelPeripheralConnection];
}

- (void)stopScanBuleToothBracelet{

    [self.buleToothTool stopScanBuleToothDevice];
}

- (void)sendWithdata:(NSData *)data{

    [self.buleToothTool writeChar:data];
}

#pragma mark -CLBuleToothToolDelegate
- (void)scanBuleToothDeviceWithPeripheral:(NSArray *)peripheralArray{

    if (self.scanSuccess) {
        self.scanSuccess(peripheralArray);
    }
}

- (void)buleToothTool:(CLBuleToothTool *)buleToothTool didConnectPeripheral:(CBPeripheral *)peripheral{
    
    if (self.connectSuccess) {
        self.connectSuccess(peripheral);
    }
    
}

- (void)buleToothTool:(CLBuleToothTool *)buleToothTool didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    if (self.errorBlock) {
        self.errorBlock(error);
    }
    [CLSeverTool showAlertWithTitle:@"提示" message:@"连接手环失败！"];
}


@end
